﻿__author__ = 'YT'

import os
import json
import time
import pygame as pg
from .. import tool
from .. import constants as c
from .. import AStarSearch
from .. import gameAI
from .. import myAI

from ..component import map, entity


# 定义一个Level类，继承自tool.State类
class Level(tool.State):
    # 初始化函数
    def __init__(self):
        # 调用父类tool.State的初始化函数
        tool.State.__init__(self)
    
    def startup(self, current_time, persist):
        # 把persist中的参数赋值给game_info
        self.game_info = persist
        # 把game_info赋值给persist
        self.persist = self.game_info
        # 把当前时间赋值给game_info
        self.game_info[c.CURRENT_TIME] = current_time

        # 加载地图
        self.loadMap()
        # 获取地图网格
        grid = self.map_data[c.MAP_GRID] if c.MAP_GRID in self.map_data else None
        # 创建地图
        self.map = map.Map(c.GRID_X_LEN, c.GRID_Y_LEN, grid)
        # 设置组
        self.setupGroup()
        # 状态设置为空闲
        self.state = c.IDLE
    
    def loadMap(self):
        # 定义地图文件名
        map_file = 'level_' + str(self.game_info[c.LEVEL_NUM]) + '.json'
        # 定义地图文件路径
        file_path = os.path.join('source', 'data', 'map', map_file)
        # 打开地图文件
        f = open(file_path)
        # 读取地图文件数据
        self.map_data = json.load(f)
        # 关闭地图文件
        f.close()
    
    def setupGroup(self):
        # 创建实体组1
        self.group1 = entity.EntityGroup(0)
        # 根据地图数据创建实体组1的实体
        self.group1.createEntity(self.map_data[c.GROUP1], self.map)
        # 创建实体组2
        self.group2 = entity.EntityGroup(1)
        # 根据地图数据创建实体组2的实体
        self.group2.createEntity(self.map_data[c.GROUP2], self.map)

    def getActiveEntity(self):
        # 获取组1和组2中活跃的实体
        entity1 = self.group1.getActiveEntity()
        entity2 = self.group2.getActiveEntity()
        #if entity1 and entity2:
        #    # 如果实体1和实体2都存在，比较它们的移动速度
        #    if entity1.attr.speed >= entity2.attr.speed:
        #        # 如果实体1的移动速度大于等于实体2，则选择实体1和组1
        #        entity, group = entity1, self.group1
        #    else:
        #        # 否则选择实体2和组2
        #        entity, group = entity2, self.group2
        #elif entity1:
        #    # 如果只有实体1存在，则选择实体1和组1
        #    entity, group = entity1, self.group1
        #elif entity2:
        #    # 如果只有实体2存在，则选择实体2和组2
        #    entity, group = entity2, self.group2
        #else:
        #    # 如果两个实体都不存在，则返回None
        #    return None

        # 这里不通过移动速度判断来抢点运行
        if entity1:
            entity, group = entity1, self.group1
        elif entity2:
            entity, group = entity2, self.group2
        else:
            return None
        return (entity, group)
        
    def update(self, surface, current_time, mouse_pos):
        # 更新当前时间
        self.current_time = self.game_info[c.CURRENT_TIME] = current_time
        # 如果当前状态为空闲
        if self.state == c.IDLE:
            # 如果group1或group2为空
            if self.group1.isEmpty() or self.group2.isEmpty():
                # 设置done为True
                self.done = True
                if self.group1.isEmpty():
                    #self.game_info[c.LEVEL_NUM] += 1
                    #self.next = c.LEVEL
                    print("####################")
                    print("####################")
                    print('Group Red win!')
                    print("####################")
                    print("####################")
                    self.state == c.GAME_OVER
                    time.sleep(10) # Sleep for 10 seconds
                else:
                    print("####################")
                    print("####################")
                    print('Group Blue win!')
                    print("####################")
                    print("####################")
                    self.state == c.GAME_OVER
                    time.sleep(10) # Sleep for 10 seconds
            else:
                # 如果没有选中实体，则获取活动实体
                result = self.getActiveEntity()
                # 如果获取到了实体
                if result is not None:
                    # 获取实体和组
                    entity, group = result
                    # 将实体设置为活动实体
                    self.map.active_entity = entity
                    # 消耗实体
                    group.consumeEntity()
                    # 设置状态为选择
                    self.state = c.SELECT
                else:
                    # 如果都没有选中，则两个组轮换
                    self.group1.nextTurn()
                    self.group2.nextTurn()
        elif self.state == c.SELECT:
            if self.map.active_entity.group_id == 0:
                #[蓝方group1 - 对手是红方group2][AI模式] 这里使用的开发的AI(基于运筹学)
                # 如果需要可以使用原有的AI进行测试也就是gameAI
                # #(map_x, map_y, enemy) = gameAI.getAction(self.map.active_entity, self.map, self.group2.group)
                (map_x, map_y, enemy) = myAI.getAction(self.map.active_entity, self.map, self.group2.group, name = "BLUE AI")
                print('pos(%d, %d)' % (map_x, map_y))
                self.map.active_entity.setDestination(map_x, map_y, enemy)
                self.state = c.ENTITY_ACT
            else:
                # [手动模式]
                #self.map.updateMap()
                #if mouse_pos is not None:
                #    self.mouseClick(mouse_pos[0], mouse_pos[1])
                #[红方group2 - 对手是蓝方group1][AI模式] 这里使用的开发的AI(基于运筹学)
                (map_x, map_y, we) = myAI.getAction(self.map.active_entity, self.map, self.group1.group, name = "RED AI")
                print('pos(%d, %d)' % (map_x, map_y))
                self.map.active_entity.setDestination(map_x, map_y, we)
                self.state = c.ENTITY_ACT

        elif self.state == c.ENTITY_ACT:
            # 更新地图
            self.map.updateMap()
            # 更新玩家1
            self.group1.update(self.game_info, self.map)
            # 更新玩家2
            self.group2.update(self.game_info, self.map)
            # 如果实体处于空闲状态
            if self.map.active_entity.state == c.IDLE:
                # 状态变为空闲
                self.state = c.IDLE

        self.draw(surface)

    def mouseClick(self, mouse_x, mouse_y):
        # 检查当前状态是否为SELECT
        if self.state == c.SELECT:
            # 如果地图检查鼠标点击位置有效
            if self.map.checkMouseClick(mouse_x, mouse_y):
                # 更新状态为ENTITY_ACT
                self.state = c.ENTITY_ACT
        
    def draw(self, surface):
        # 绘制地图背景
        self.map.drawBackground(surface)
        # 绘制第一组元素
        self.group1.draw(surface)
        # 绘制第二组元素
        self.group2.draw(surface)
        # 绘制鼠标显示
        self.map.drawMouseShow(surface)